package gjtx13;

import gjtx课堂.gjtx练习8.XMLOp;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class DealWith {
    public static void main(String[] args) {
        // readALL();
        // seek(2953);
        modify(2952,2000);
        //buy(2950, 1);
       // increase(false,null,2952,"巧克力棒",15.5,3000,"袋");
    }
    //1：读取products.xml中的商品信息，输出。
    public static void readALL() {
        Document doc=fetch();
        Element root = doc.getRootElement();
        String name = root.attributeValue("name");
        System.out.println("根节点名称：" + root.getName() + ",name=" + name);
        List<Node> list = doc.selectNodes("shop/product");
        for (Node node : list) {
            Element element = (Element) node;
            boolean discount = Boolean.parseBoolean(element.attributeValue("discount"));
            String factoryaddr = element.attributeValue("factoryaddr");
            int itemno = Integer.parseInt(element.elementTextTrim("itemno"));
            String name1 = element.elementTextTrim("name");
            double price = Double.parseDouble(element.elementTextTrim("price"));
            int stockcount = Integer.parseInt(element.elementTextTrim("stockcount"));
            String unit = element.elementTextTrim("unit");
            System.out.println(discount + "\t" + factoryaddr + "\t" + itemno + "\t" + name1 + "\t" + price + "\t" + stockcount + "\t" + unit);
        }
    }
//2：查找商品信息：根据输入的商品号，输出对应的商品信息。
    public static void seek(int itemno) {
        Document doc=fetch();
        List<Node> list = doc.selectNodes("shop/product");
        for (Node node : list) {
            Element element = (Element) node;
            int itemno1 = Integer.parseInt(element.elementTextTrim("itemno"));
            if (itemno1 == itemno) {
                boolean discount = Boolean.parseBoolean(element.attributeValue("discount"));
                String factoryaddr = element.attributeValue("factoryaddr");
                String name= element.elementTextTrim("name");
                double price = Double.parseDouble(element.elementTextTrim("price"));
                int stockcount = Integer.parseInt(element.elementTextTrim("stockcount"));
                String unit = element.elementTextTrim("unit");
                System.out.println(discount + "\t" + factoryaddr + "\t" + itemno + "\t" + name + "\t" + price + "\t" + stockcount + "\t" + unit);
                return;
            }
        }
    }
//3：修改products.xml，输入商品编号（itemno）和数量，
// 修改对应商品的数量（stockcount）；没有找到商品号，给出提示。
    public static void modify(int itemno,int stockcount){
        Document doc=fetch();
        List<Node> list = doc.selectNodes("shop/product");
        for (Node node : list) {
            Element element = (Element) node;
            int itemno1 = Integer.parseInt(element.elementTextTrim("itemno"));
            if (itemno1==itemno){
                element.selectSingleNode("stockcount").setText(String.valueOf(stockcount));
                write(doc);
                return;
            }
        }
        System.out.println("没有找到商品号");
    }
/**4：以products.xml作为基础，实现客户购买的方法，
* 输入商品号和购买数量，计算应付金额，
*如果是折扣商品，打七折；
  *  如果购买数量超过库存量，给出提示；商品不存在，给出提示；
 *  购买成功，扣除相应的数量。最后输出应付款的金额。
 */
    public static void buy(int itemno, int quantity) {
        Document doc=fetch();
        List<Node> list = doc.selectNodes("shop/product");
        for (Node node : list) {
            Element element = (Element) node;
            int itemno1 = Integer.parseInt(element.elementTextTrim("itemno"));//判断商品是否存在
            if (itemno1 == itemno) {
                int stockcount = Integer.parseInt(element.elementTextTrim("stockcount"));
                if (stockcount >= quantity) {//判断库存是否足够？？？
                    boolean discount = Boolean.parseBoolean(element.attributeValue("discount"));//判断是否打折？？？？
                    double price = Double.parseDouble(element.elementTextTrim("price"));//商品单价；
                    int stockcount1 = stockcount - quantity;
                    double money = 0.0;
                    if (discount == true) {//打折：折扣七折
                        money = price * quantity * 0.7;
                        System.out.println("客户应付款：" + money + "元。");
                    } else {//不打折：全款；
                        money = price * quantity;
                        System.out.println("客户应付款：" + money + "元。");
                    }
                    element.selectSingleNode("stockcount").setText(String.valueOf(stockcount1));
                    write(doc);
                    return;
                }
                System.out.println("购买数量超过库存量！！！！");
                return;
            }
        }
        System.out.println("您购买的商品不存在！！！");
    }
    //5:增加新商品的功能，要求商品号和商品名称都不能重复（即不能和已经存在的重复）
    public static void increase(boolean discount,String factoryaddr, int itemno,String name,double price,int stockcount,String unit){
        Document doc=fetch();
        List list1= doc.selectNodes("/shop/product[itemno='" + itemno + "']");
        List list2= doc.selectNodes("/shop/product[name='" + name + "']");
        if(list1.size()==0&&list2.size()==0) {
            Element  root = doc.getRootElement();//找到根元素
            Element element = root.addElement("product");//添加节点；
            element.addAttribute("discount",String.valueOf(discount));
            if (factoryaddr==null){
                element.addElement("itemno").setText(String.valueOf(itemno));
                element.addElement("name").setText(name);
                element.addElement("price").setText(String.valueOf(price));
                element.addElement("stockcount").setText(String.valueOf(stockcount));
                element.addElement("unit").setText(unit);
                write(doc);
                return;
            }else {
                element.addAttribute("factoryaddr",factoryaddr);
                element.addElement("itemno").setText(String.valueOf(itemno));
                element.addElement("name").setText(name);
                element.addElement("price").setText(String.valueOf(price));
                element.addElement("stockcount").setText(String.valueOf(stockcount));
                element.addElement("unit").setText(unit);
                write(doc);
                return;
            }
        }else {
            System.out.println("商品号或商品名称重复！！！");
            return;
        }
    }
    //对读取进行封装；
    public static Document  fetch(){
        SAXReader reader = new SAXReader();
        Document doc = null;
        try {
            doc = reader.read(XMLOp.class.getClassLoader().getResourceAsStream("data/products.xml"));
        } catch (DocumentException e) {
            e.printStackTrace();
            return null;
        }
        return doc;
    }
    //对写入进行封装；
    public static void write(Document doc) {
        try {
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("utf-8");
            XMLWriter xw = new XMLWriter(new FileWriter("Java高级特性/src/data/products.xml"), format);
            xw.write(doc);
            xw.close();
        } catch (IOException ee) {
            ee.printStackTrace();
        }
    }
}
